package cn.edu.hstc.wm.service;

import java.io.IOException;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import cn.edu.hstc.wm.AppConfigs;

/**
 * WebService 获取SoapObject封装包的核心方法
 * 
 */
public class SoapService {
	/**
	 * WebService 命名空间
	 */
	public static final String SERVICE_NS = AppConfigs.SERVICE_NS;

	/**
	 * 提供WebService服务的地址
	 */
	public static final String SERVICE_URL = AppConfigs.WEB_SERVICE_URL;

	/**
	 * 根据传入的请求 和参数获取SoapObject对象
	 * 
	 * @param soapAction
	 *            请求
	 * @param params
	 *            请求参数
	 * @return SoapObject
	 * @throws Exception
	 */
	public static SoapObject getSoapObject(String soapAction, List<BasicNameValuePair> params) throws Exception {
		// 创建HttpTransportSE 传输对象
		HttpTransportSE httpTransportSE = new HttpTransportSE(SERVICE_URL, AppConfigs.HTTP_TIMEOUT);
		// 开启调试
		httpTransportSE.debug = true;

		// 使用SOAP1.1协议创建Envelope对象 ,ver12版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);

		// 实例化SoapObject对象
		SoapObject soapObject = new SoapObject(SERVICE_NS, soapAction);

		// 如果有参数就添加参数
		if (params != null && params.size() > 0) {
			for (int i = 0; i < params.size(); i++) {
				soapObject.addProperty(params.get(i).getName(), params.get(i).getValue());
			}
		}

		// ==
		// envelope.setOutputSoapObject(soapObject);
		envelope.bodyOut = soapObject;

		// 设置与.net提供的web service保持较好的兼容性
		// envelope.dotNet = true;

		// 调用web service ,如果异常则直接返回空
		try {
			httpTransportSE.call(null, envelope);
		} catch (HttpResponseException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (XmlPullParserException e) {
			e.printStackTrace();
			return null;
		}

		// 有响应且获取内容不为空
		try {
			if (envelope.getResponse() != null) {
				// 获取服务器响应返回的soap消息
				// SoapObject detail = (SoapObject) envelope.getResponse();
				Log.d(" ", envelope.toString());
				return (SoapObject) envelope.bodyIn;
			}
		} catch (SoapFault e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
}
